<template>
  <div class="product-add-container">
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">{{ isEdit ? '编辑商品' : '新增商品' }}</h2>
        <el-button icon="el-icon-back" @click="$router.go(-1)">返回</el-button>
      </div>
    </div>

    <div class="content-container">
      <div class="section-card">
        <div class="section-header">
          <h3>商品信息</h3>
        </div>
        <el-form
          ref="productForm"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="right"
          v-loading="loading"
        >
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品分类" prop="category">
                <el-select v-model="form.category" placeholder="请选择商品分类">
                  <el-option
                    v-for="item in categoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="商品价格" prop="price">
                <el-input-number
                  v-model="form.price"
                  :min="0"
                  :precision="0"
                  :step="100"
                  controls-position="right"
                  style="width: 200px"
                ></el-input-number>
                <span class="unit-label">积分</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库存数量" prop="stock">
                <el-input-number
                  v-model="form.stock"
                  :min="0"
                  :precision="0"
                  controls-position="right"
                  style="width: 200px"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="商品状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio :label="'在售'">在售</el-radio>
                  <el-radio :label="'已下架'">已下架</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="商品图片" prop="image">
                <el-upload
                  class="product-image-uploader"
                  action="http://localhost:3000/api/uploads"
                  :show-file-list="false"
                  :on-success="handleImageSuccess"
                  :before-upload="beforeImageUpload"
                >
                  <img v-if="form.image" :src="form.image" class="product-image" />
                  <i v-else class="el-icon-plus product-image-uploader-icon"></i>
                </el-upload>
                <div class="image-tip">建议尺寸：400x400px，大小不超过2MB</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="商品描述" prop="description">
                <el-input
                  type="textarea"
                  v-model="form.description"
                  :rows="4"
                  placeholder="请输入商品描述"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 商品规格管理 -->
      <div class="section-card" v-if="isEdit || tempProductId">
        <div class="section-header">
          <h3>规格管理</h3>
          <el-button type="primary" size="small" @click="showAddSpecDialog">添加规格</el-button>
        </div>
        <el-table :data="specs" style="width: 100%" v-loading="specsLoading" border>
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="规格名称" width="150"></el-table-column>
          <el-table-column prop="values" label="规格值">
            <template slot-scope="scope">
              <el-tag
                v-for="(value, index) in scope.row.values"
                :key="index"
                style="margin-right: 5px"
              >{{ value }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" @click="deleteSpec(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- SKU管理 -->
      <div class="section-card" v-if="(isEdit || tempProductId) && specs.length > 0">
        <div class="section-header">
          <h3>SKU管理</h3>
          <el-button type="primary" size="small" @click="showAddSkuDialog">添加SKU</el-button>
        </div>
        <el-table :data="skus" style="width: 100%" v-loading="skusLoading" border>
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column label="规格组合" width="250">
            <template slot-scope="scope">
              <div v-for="(value, key) in scope.row.specs" :key="key" style="margin-bottom: 5px">
                {{ key }}:
                <el-tag>{{ value }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格(积分)" width="120"></el-table-column>
          <el-table-column prop="stock" label="实际库存" width="120"></el-table-column>
          <el-table-column prop="availableStock" label="可用库存" width="120"></el-table-column>
          <el-table-column label="图片" width="100">
            <template slot-scope="scope">
              <img v-if="scope.row.image" :src="scope.row.image" style="width: 50px; height: 50px" />
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="editSku(scope.row)"
                style="margin-right: 5px"
              >编辑</el-button>
              <el-button type="danger" size="mini" @click="deleteSku(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="section-card">
        <div class="form-actions">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button
            type="success"
            v-if="!isEdit && !tempProductId"
            @click="saveProductTemp"
          >临时保存并添加规格</el-button>
        </div>
      </div>
    </div>

    <!-- 添加规格对话框 -->
    <el-dialog title="添加规格" :visible.sync="specDialogVisible" width="500px">
      <el-form ref="specForm" :model="specForm" :rules="specRules" label-width="100px">
        <el-form-item label="规格名称" prop="name">
          <el-input v-model="specForm.name" placeholder="如：颜色、尺寸等"></el-input>
        </el-form-item>
        <el-form-item label="规格值" prop="values">
          <el-tag
            :key="tag"
            v-for="tag in specForm.values"
            closable
            :disable-transitions="false"
            @close="handleSpecValueClose(tag)"
            style="margin-right: 5px; margin-bottom: 5px"
          >{{ tag }}</el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputSpecVisible"
            v-model="inputSpecValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputSpecConfirm"
            @blur="handleInputSpecConfirm"
          ></el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInputSpec">+ 添加规格值</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="specDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSpec">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加SKU对话框 -->
    <el-dialog title="添加SKU" :visible.sync="skuDialogVisible" width="600px">
      <el-form ref="skuForm" :model="skuForm" :rules="skuRules" label-width="100px">
        <el-form-item label="规格组合" prop="specs">
          <div v-for="spec in specs" :key="spec.id" style="margin-bottom: 10px">
            <span style="display: inline-block; width: 100px">{{ spec.name }}:</span>
            <el-select
              :value="skuForm.specs[spec.name]"
              @change="(value) => handleSpecChange(spec.name, value)"
              placeholder="请选择"
              style="width: 200px"
            >
              <el-option v-for="value in spec.values" :key="value" :label="value" :value="value"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="skuForm.price" :min="0" :step="100" style="width: 200px"></el-input-number>
          <span class="unit-label">积分</span>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="skuForm.stock" :min="0" style="width: 200px"></el-input-number>
        </el-form-item>
        <el-form-item label="SKU图片" prop="image">
          <el-upload
            class="product-image-uploader"
            action="http://localhost:3000/api/uploads"
            :show-file-list="false"
            :on-success="handleSkuImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <img
              v-if="skuForm.image"
              :src="skuForm.image"
              class="product-image"
              style="width: 100px; height: 100px"
            />
            <i
              v-else
              class="el-icon-plus product-image-uploader-icon"
              style="width: 100px; height: 100px; line-height: 100px"
            ></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="skuDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSku">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { getProductDetail, addProduct, updateProduct } from '@/api/product'
import {
  getProductSpecs,
  addProductSpec,
  deleteProductSpec,
} from '@/api/product'
import {
  getProductSkus,
  addProductSku,
  deleteProductSku,
  updateProductSku,
} from '@/api/product'
import { uploadFile } from '@/api/upload'

export default {
  name: 'ProductAdd',
  data() {
    return {
      isEdit: false,
      loading: false,
      tempProductId: null, // 临时产品ID，用于新增商品时添加规格和SKU
      form: {
        id: null,
        name: '',
        category: '',
        price: 100,
        stock: 0,
        availableStock: 0,
        status: '在售',
        image: '',
        description: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          {
            min: 2,
            max: 50,
            message: '长度在 2 到 50 个字符',
            trigger: 'blur',
          },
        ],
        category: [
          { required: true, message: '请选择商品分类', trigger: 'change' },
        ],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        stock: [{ required: true, message: '请输入库存数量', trigger: 'blur' }],
        status: [
          { required: true, message: '请选择商品状态', trigger: 'change' },
        ],
        image: [
          { required: true, message: '请上传商品图片', trigger: 'change' },
        ],
        description: [
          { required: true, message: '请输入商品描述', trigger: 'blur' },
        ],
      },
      categoryOptions: [
        { value: '数码', label: '数码' },
        { value: '食品', label: '食品' },
        { value: '服装', label: '服装' },
        { value: '家居', label: '家居' },
      ],

      // 规格相关
      specs: [],
      specsLoading: false,
      specDialogVisible: false,
      specForm: {
        name: '',
        values: [],
      },
      specRules: {
        name: [{ required: true, message: '请输入规格名称', trigger: 'blur' }],
        values: [
          {
            required: true,
            type: 'array',
            message: '请添加至少一个规格值',
            trigger: 'change',
          },
        ],
      },
      inputSpecVisible: false,
      inputSpecValue: '',

      // SKU相关
      skus: [],
      skusLoading: false,
      skuDialogVisible: false,
      skuForm: {
        specs: {},
        price: 0,
        stock: 0,
        image: '',
      },
      editingSkuId: null, // 用于标识当前是否在编辑SKU
      skuRules: {
        price: [{ required: true, message: '请输入SKU价格', trigger: 'blur' }],
        stock: [{ required: true, message: '请输入SKU库存', trigger: 'blur' }],
      },
    }
  },
  created() {
    // 获取路由参数，判断是编辑还是新增
    const id = this.$route.query.id
    if (id) {
      this.isEdit = true
      this.fetchProductDetail(id)
      this.fetchProductSpecs(id)
      this.fetchProductSkus(id)
    }
  },
  methods: {
    // 获取商品详情
    fetchProductDetail(id) {
      this.loading = true
      getProductDetail(id)
        .then(res => {
          this.form = res.data
        })
        .catch(error => {
          console.error('获取商品详情失败', error)
          this.$message.error('获取商品详情失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取商品规格列表
    fetchProductSpecs(productId) {
      this.specsLoading = true
      getProductSpecs(productId)
        .then(res => {
          this.specs = res.data || []
        })
        .catch(error => {
          console.error('获取规格列表失败', error)
          this.$message.error('获取规格列表失败')
        })
        .finally(() => {
          this.specsLoading = false
        })
    },

    // 获取商品SKU列表
    fetchProductSkus(productId) {
      this.skusLoading = true
      getProductSkus(productId)
        .then(res => {
          this.skus = res.data || []
        })
        .catch(error => {
          console.error('获取SKU列表失败', error)
          this.$message.error('获取SKU列表失败')
        })
        .finally(() => {
          this.skusLoading = false
        })
    },

    // 显示添加规格对话框
    showAddSpecDialog() {
      this.specForm = {
        name: '',
        values: [],
      }
      this.specDialogVisible = true
    },

    // 显示添加规格值输入框
    showInputSpec() {
      this.inputSpecVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 处理规格值输入确认
    handleInputSpecConfirm() {
      let inputValue = this.inputSpecValue
      if (inputValue) {
        if (this.specForm.values.indexOf(inputValue) === -1) {
          this.specForm.values.push(inputValue)
        }
      }
      this.inputSpecVisible = false
      this.inputSpecValue = ''
    },

    // 处理规格值关闭
    handleSpecValueClose(tag) {
      this.specForm.values.splice(this.specForm.values.indexOf(tag), 1)
    },

    // 保存规格
    saveSpec() {
      this.$refs.specForm.validate(valid => {
        if (valid) {
          const data = {
            name: this.specForm.name,
            values: this.specForm.values,
            productId: this.form.id,
          }

          addProductSpec(this.form.id, data)
            .then(() => {
              this.$message.success('添加规格成功')
              this.specDialogVisible = false
              this.fetchProductSpecs(this.form.id)
            })
            .catch(error => {
              console.error('添加规格失败', error)
              this.$message.error('添加规格失败')
            })
        }
      })
    },

    // 删除规格
    deleteSpec(row) {
      this.$confirm('确定要删除该规格吗？关联的SKU也会被删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteProductSpec(row.id)
            .then(() => {
              this.$message.success('删除规格成功')
              this.fetchProductSpecs(this.form.id)
              this.fetchProductSkus(this.form.id)
            })
            .catch(error => {
              console.error('删除规格失败', error)
              this.$message.error('删除规格失败')
            })
        })
        .catch(() => {
          // 取消删除
        })
    },

    // 显示添加SKU对话框
    showAddSkuDialog() {
      this.editingSkuId = null // 重置编辑状态
      this.skuForm = {
        specs: {},
        price: this.form.price,
        stock: 0,
        image: '',
      }

      // 初始化规格选择
      this.specs.forEach(spec => {
        if (spec.values.length > 0) {
          this.skuForm.specs[spec.name] = spec.values[0]
        }
      })

      this.skuDialogVisible = true
    },

    // SKU图片上传成功回调
    handleSkuImageSuccess(res, file) {
      this.skuForm.image = res.data.url
    },

    // 保存SKU
    saveSku() {
      this.$refs.skuForm.validate(valid => {
        if (valid) {
          // 如果是编辑模式
          if (this.editingSkuId) {
            // 验证规格组合是否与其他SKU冲突
            const specCombination = JSON.stringify(this.skuForm.specs)
            const conflictSku = this.skus.find(sku => {
              return (
                sku.id !== this.editingSkuId &&
                JSON.stringify(sku.specs) === specCombination
              )
            })

            if (conflictSku) {
              this.$message.error('该规格组合已存在于其他SKU中')
              return
            }

            const updateData = {
              specs: this.skuForm.specs,
              price: this.skuForm.price,
              stock: this.skuForm.stock,
              image: this.skuForm.image,
            }

            // 调用更新SKU接口
            updateProductSku(this.editingSkuId, updateData)
              .then(() => {
                this.$message.success('更新SKU成功')
                this.skuDialogVisible = false
                this.fetchProductSkus(this.form.id)
              })
              .catch(error => {
                console.error('更新SKU失败', error)
                this.$message.error('更新SKU失败')
              })
          } else {
            // 新增模式
            // 验证规格组合是否已存在
            const specCombination = JSON.stringify(this.skuForm.specs)
            const exists = this.skus.some(sku => {
              return JSON.stringify(sku.specs) === specCombination
            })

            if (exists) {
              this.$message.error('该规格组合已存在')
              return
            }

            const data = {
              specs: this.skuForm.specs,
              price: this.skuForm.price,
              stock: this.skuForm.stock,
              image: this.skuForm.image,
              productId: this.form.id,
            }

            addProductSku(this.form.id, data)
              .then(() => {
                this.$message.success('添加SKU成功')
                this.skuDialogVisible = false
                this.fetchProductSkus(this.form.id)
              })
              .catch(error => {
                console.error('添加SKU失败', error)
                this.$message.error('添加SKU失败')
              })
          }
        }
      })
    },

    // 删除SKU
    deleteSku(row) {
      this.$confirm('确定要删除该SKU吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteProductSku(row.id)
            .then(() => {
              this.$message.success('删除SKU成功')
              this.fetchProductSkus(this.form.id)
            })
            .catch(error => {
              console.error('删除SKU失败', error)
              this.$message.error('删除SKU失败')
            })
        })
        .catch(() => {
          // 取消删除
        })
    },

    // 图片上传成功回调
    handleImageSuccess(res, file) {
      // 使用后端返回的图片URL
      this.form.image = res.data.url
    },
    // 图片上传前的校验
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传的图片只能是图片格式!')
        return false
      }

      if (!isLt2M) {
        this.$message.error('上传的图片大小不能超过 2MB!')
        return false
      }

      //   // 使用实际上传接口
      //   uploadFile(file)
      //     .then(res => {
      //       this.form.image = res.data.url
      //     })
      //     .catch(error => {
      //       console.error('上传图片失败', error)
      //       this.$message.error('上传图片失败')
      //     })

      //   return false // 阻止el-upload默认上传
    },
    // 表单提交
    submitForm() {
      this.$refs.productForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 创建商品时移除id字段
          const formData = {}
          if (!this.isEdit) {
            delete formData.id
          }
          let key = [
            'category',
            'description',
            'image',
            'name',
            'price',
            'status',
            'stock',
          ]
          key.forEach(item => {
            formData[item] = this.form[item]
          })

          const saveRequest = this.isEdit
            ? updateProduct(this.form.id, formData)
            : addProduct(formData)

          saveRequest
            .then(() => {
              this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
              this.$router.push('/product/list')
            })
            .catch(error => {
              console.error(
                this.isEdit ? '更新商品失败' : '新增商品失败',
                error
              )
              this.$message.error(this.isEdit ? '更新商品失败' : '新增商品失败')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.productForm.resetFields()
      if (this.isEdit) {
        this.fetchProductDetail(this.form.id)
      }
    },
    // 处理规格选择变化
    handleSpecChange(specName, value) {
      this.$set(this.skuForm.specs, specName, value)
      this.$forceUpdate()
      console.log(this.skuForm)
    },
    // 临时保存商品
    saveProductTemp() {
      this.$refs.productForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 创建表单数据
          const formData = {}
          let key = [
            'category',
            'description',
            'image',
            'name',
            'price',
            'status',
            'stock',
          ]
          key.forEach(item => {
            formData[item] = this.form[item]
          })

          // 临时保存商品
          addProduct(formData)
            .then(response => {
              // 获取返回的商品ID
              if (response.code === 200 && response.data && response.data.id) {
                this.tempProductId = response.data.id
                this.form.id = response.data.id // 同时更新表单ID
                this.$message.success('商品临时保存成功，请继续添加规格和SKU')
              } else {
                this.$message.error('商品保存失败，请重试')
              }
            })
            .catch(error => {
              console.error('商品保存失败', error)
              this.$message.error('商品保存失败，请重试')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    // 编辑SKU
    editSku(row) {
      this.editingSkuId = row.id
      this.skuForm = {
        specs: { ...row.specs },
        price: row.price,
        stock: row.stock,
        image: row.image,
      }
      this.skuDialogVisible = true
    },
  },
}
</script>

<style scoped>
.product-add-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: #ffffff;
  border-radius: 8px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.section-card {
  background: #ffffff;
  padding: 24px;
  border-radius: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e6eb;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.product-image-uploader {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: inline-block;
  vertical-align: top;
}

.product-image-uploader:hover {
  border-color: #409eff;
}

.product-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.product-image {
  width: 150px;
  height: 150px;
  display: block;
  object-fit: cover;
}

.image-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

.unit-label {
  margin-left: 10px;
  color: #606266;
}

.form-actions {
  /* margin-top: 32px; */
  text-align: center;
}
</style> 